package com.freework.util.excel.read.service;


import java.io.File;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBException;

import com.freework.util.XMLUtil;
import com.freework.util.excel.read.service.rowToObject.RowToObjectFactory;
import com.freework.util.excel.read.service.rowToObject.RowToObjectI;
import com.freework.util.excel.read.service.rowToObject.ValueFormat;
import com.freework.util.excel.read.service.rowToObject.ValueFormatFactory;

import com.freework.util.excel.read.vo.ColVO;
import com.freework.util.excel.read.vo.ObjectFactory;
import com.freework.util.excel.read.vo.SheetVO;

public class ReadExcel {
	static ReadSheelDataI read=new ReadSheelDataPOI();
	public static <T> List<T> getData(Class<T> clazz,SheetVO vo,InputStream in){
		RowToObjectI rowToObject=	RowToObjectFactory.getRowToObject(clazz, vo.getCols());
		return (List<T>) read.getData(vo, rowToObject,in);
	} 
	
	public static  List<Map> getData(SheetVO vo,InputStream in){
		RowToObjectI rowToObject=	RowToObjectFactory.getRowToObject(null, vo.getCols());
		return read.getData(vo, rowToObject,in);
	} 
	public static  List<List> getData(List<SheetVO> list,Class clazz[],InputStream in){
		RowToObjectI rowToObjects[]=new RowToObjectI[list.size()];
		int i=0;
		for (SheetVO sheetVO : list) {
			rowToObjects[i]=	RowToObjectFactory.getRowToObject(clazz[i], sheetVO.getCols());

			i++;
		}
		return read.getData(list, Arrays.asList(rowToObjects),in);
	} 
	public static  List<List> getData(List<SheetVO> list,InputStream in){
		RowToObjectI rowToObjects[]=new RowToObjectI[list.size()];
		int i=0;
		for (SheetVO sheetVO : list) {
			rowToObjects[i]=	RowToObjectFactory.getRowToObject(null, sheetVO.getCols());
			i++;
		}
		return read.getData(list, Arrays.asList(rowToObjects),in);
	} 
	
	public static List getData(String xmlPath,InputStream in) throws JAXBException{
		return getData(getSheet(xmlPath), in);
		
		
	}
	private static SheetVO getSheet(String xmlPath) throws JAXBException{
		SheetVO sheetVO=(SheetVO) XMLUtil.xmlToObject(new File(xmlPath),ObjectFactory.class);
		ValueFormatFactory factory=sheetVO.getValueFormatFactory();
		if(factory!=null){
			List<ColVO> cols=sheetVO.getCols();
			for (ColVO colVO : cols) {
				if(colVO.getFormat()==null){
					ValueFormat valueFormat=factory.getValueFormat(sheetVO, colVO);
					if(valueFormat!=null)
						colVO.setFormat(valueFormat);
				}
			}
		}
		return sheetVO;
	}
	
	
	public static <T> List<T> getData(String xmlPath,Class<T> clazz,InputStream in) throws JAXBException{
		return getData(clazz,getSheet(xmlPath), in);
		
		
	}
	

}
